import axios from 'axios'
import { Loading } from 'element-ui'
import router from '@/router/index'
import store from '@/store'
axios.defaults.baseURL = 'http://www.liulongbin.top:3008'
export default axios
let loading = null
axios.interceptors.request.use(
  function (config) {
    if (config.url.startsWith('/my')) {
      config.headers.Authorization = localStorage.getItem('token')
    }
    loading = Loading.service({
      lock: true,
      text: '正在加载中',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

axios.interceptors.response.use(
  function (response) {
    loading.close()
    return response
  },
  function (error) {
    console.dir(error)
    if (error.response.status === 401 && error.response.data.code === 1) {
      localStorage.removeItem('token')
      router.push('/login')
      store.commit('user/setUserInfo', {})
    }
    loading.close()
    return Promise.reject(error)
  }
)
